<script setup lang="ts">
import { Icon } from 'vant'
import { ref, watch, onMounted, nextTick } from 'vue'

interface Reference {
  title: string;
  url: string;
  content: string;
  [key: string]: any;
}

const props = defineProps({
  show: Boolean,
  references: {
    type: Array as () => Reference[],
    default: () => []
  },
  embed: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:show', 'select'])

// 动画和手势相关状态
const popupRef = ref<HTMLElement | null>(null)
const startY = ref(0)
const moveY = ref(0)
const popupHeight = ref(0)
const isDragging = ref(false)
const opacity = ref(1)

// 初始化弹窗高度
onMounted(() => {
  if (props.embed) {
    nextTick(() => {
      if (popupRef.value) {
        popupHeight.value = popupRef.value.offsetHeight
      }
    })
  }
})

// 监听show变化，重置状态
watch(() => props.show, (newVal) => {
  if (newVal && props.embed) {
    moveY.value = 0
    opacity.value = 1
    isDragging.value = false
    nextTick(() => {
      if (popupRef.value) {
        popupHeight.value = popupRef.value.offsetHeight
      }
    })
  }
})

// 关闭弹窗
const closePopup = () => {
  emit('update:show', false)
}

// 处理遮罩层点击
const handleOverlayClick = (e: MouseEvent) => {
  // 只有点击遮罩层本身才关闭弹窗，防止点击内容区域时关闭
  if (e.target === e.currentTarget) {
    closePopup()
  }
}

// 处理开始拖拽
const handleTouchStart = (e: TouchEvent) => {
  if (!props.embed) return
  startY.value = e.touches[0].clientY
  isDragging.value = true
}

// 处理拖拽中
const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value || !props.embed) return
  const currentY = e.touches[0].clientY
  const diff = currentY - startY.value
  
  // 只允许向下拖动
  if (diff > 0) {
    moveY.value = diff
    // 根据拖动距离计算透明度
    opacity.value = Math.max(0, 1 - diff / (popupHeight.value * 0.8))
  }
}

// 处理拖拽结束
const handleTouchEnd = () => {
  if (!isDragging.value || !props.embed) return
  
  // 如果拖动超过一定距离，则关闭弹窗
  if (moveY.value > popupHeight.value * 0.3) {
    closePopup()
  } else {
    // 否则恢复原位
    moveY.value = 0
    opacity.value = 1
  }
  
  isDragging.value = false
}

const selectReference = (reference: Reference) => {
  emit('select', reference)
}

const truncateText = (text: string, maxLength = 100) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

const simplifyUrl = (url: string) => {
  try {
    const urlObj = new URL(url)
    return urlObj.hostname
  } catch (e) {
    return url
  }
}
</script>

<template>
  <!-- 嵌入模式下使用内部弹窗 -->
  <transition name="fade" v-if="props.embed">
    <div 
      v-if="show" 
      class="reference-panel"
      @click="handleOverlayClick"
      :style="{ 'background-color': `rgba(0, 0, 0, ${opacity * 0.5})` }"
    >
      <div 
        ref="popupRef"
        class="reference-popup embed"
        :style="{ transform: `translateY(${moveY}px)`, opacity: opacity }"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      >
        <!-- 拖动指示条 -->
        <div class="drag-indicator"></div>
        
        <div class="reference-header">
          <div class="title">参考资料</div>
          <div class="close-btn" @click="closePopup">
            <Icon name="cross" />
          </div>
        </div>
        <div class="reference-list">
          <div 
            v-for="(ref, index) in references" 
            :key="index"
            class="reference-item"
            @click="selectReference(ref)"
          >
            <div class="reference-title">
              <span class="index">{{ index + 1 }}</span>
              <span class="text">{{ ref.title }}</span>
            </div>
            <div class="reference-content">
              {{ truncateText(ref.content) }}
            </div>
            <div class="reference-url">
              <Icon name="link" />
              <span>{{ simplifyUrl(ref.url) }}</span>
              <Icon name="arrow" class="arrow-icon" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
  
  <!-- 普通模式下使用全屏弹窗 -->
  <van-popup
    v-else
    :show="show"
    @update:show="(val) => emit('update:show', val)"
    position="bottom"
    round
    :style="{ maxHeight: '80%' }"
    class="reference-popup-container"
  >
    <div class="reference-popup">
      <div class="reference-header">
        <div class="title">参考资料</div>
        <div class="close-btn" @click="closePopup">
          <Icon name="cross" />
        </div>
      </div>
      <div class="reference-list">
        <div 
          v-for="(ref, index) in references" 
          :key="index"
          class="reference-item"
          @click="selectReference(ref)"
        >
          <div class="reference-title">
            <span class="index">{{ index + 1 }}</span>
            <span class="text">{{ ref.title }}</span>
          </div>
          <div class="reference-content">
            {{ truncateText(ref.content) }}
          </div>
          <div class="reference-url">
            <Icon name="link" />
            <span>{{ simplifyUrl(ref.url) }}</span>
            <Icon name="arrow" class="arrow-icon" />
          </div>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<style lang="scss" scoped>
.reference-popup-container {
  border-radius: 16px 16px 0 0;
}

.reference-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  transition: background-color 0.3s;
}

.reference-popup {
  padding: 0 16px;
  background-color: white;
  border-radius: 16px 16px 0 0;
  max-height: 80%;
  
  &.embed {
    height: 80%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    transition: transform 0.2s, opacity 0.2s;
    transform: translateY(0);
    
    .drag-indicator {
      position: absolute;
      top: 8px;
      left: 50%;
      transform: translateX(-50%);
      width: 36px;
      height: 4px;
      background-color: #ddd;
      border-radius: 4px;
    }
    
    .reference-header {
      margin-top: 20px;
    }
    
    .reference-list {
      flex: 1;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
    }
  }

  .reference-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    margin-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 10;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .close-btn {
      padding: 8px;
      border-radius: 50%;
      color: #999;
      
      &:active {
        background-color: #f5f5f5;
      }
    }
  }

  .reference-list {
    .reference-item {
      padding: 16px;
      margin-bottom: 12px;
      border-radius: 12px;
      background-color: #f8f9fa;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      cursor: pointer;
      transition: transform 0.2s ease, box-shadow 0.2s ease;

      &:last-child {
        margin-bottom: 20px;
      }

      &:active {
        transform: scale(0.99);
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
      }

      .reference-title {
        font-weight: bold;
        margin-bottom: 10px;
        font-size: 16px;
        display: flex;
        gap: 12px;
        
        .index {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          background-color: #4080ff;
          color: white;
          border-radius: 50%;
          font-size: 14px;
        }
        
        .text {
          color: #333;
          flex: 1;
        }
      }

      .reference-content {
        color: #666;
        font-size: 14px;
        margin-bottom: 12px;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .reference-url {
        color: #999;
        font-size: 13px;
        display: flex;
        align-items: center;
        gap: 6px;
        padding-top: 8px;
        border-top: 1px dashed #eee;
        
        .arrow-icon {
          margin-left: auto;
          color: #4080ff;
        }
      }
    }
  }
}

// 过渡动画
.fade-enter-active {
  animation: fade-in 0.3s;
}
.fade-leave-active {
  animation: fade-out 0.3s;
}

@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fade-out {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
</style>
